package org.example.algorithm.binarytree;

import org.example.algorithm.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 101. 对称二叉树
 * todo:单个队列也可以实现，每次取出两个队列操作
 */

public class IsSymmetricSolution {

    public static boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> leftQueue = new LinkedList<>();
        leftQueue.offer(root.left);
        Queue<TreeNode> rightQueue = new LinkedList<>();
        rightQueue.add(root.right);
        while (!leftQueue.isEmpty() && !rightQueue.isEmpty()) {
            TreeNode leftNode = leftQueue.poll();
            TreeNode rightNode = rightQueue.poll();
            if (leftNode == null && rightNode == null) {
                continue;
            }
            if (leftNode == null || rightNode == null) {
                return false;
            }
            if (leftNode.val != rightNode.val) {
                return false;
            }
            leftQueue.offer(leftNode.left);
            leftQueue.offer(leftNode.right);
            rightQueue.offer(rightNode.right);
            rightQueue.offer(rightNode.left);
        }
        return leftQueue.isEmpty() && rightQueue.isEmpty();
    }

    /**
     * 递归法
     * @param root
     * @return
     */
    public static boolean isSymmetric2(TreeNode root) {
        if (root == null) {
            return true;
        }
        return valueEqual(root.left, root.right);
    }

    public static Boolean valueEqual(TreeNode left, TreeNode right)
    {
        if (left == null && right == null) {
            return true;
        }
        if (left == null || right == null) {
            return false;
        }
        return left.val== right.val && valueEqual(left.left, right.right) && valueEqual(left.right, right.left);
    }
}
